package utils

import (
	"crypto/rand"
	"encoding/json"
	"math/big"
)

var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")

// RandomString 生成随机字符串
func RandomString(n int) (string, error) {
	b := make([]rune, n)
	for i := range b {
		num, err := rand.Int(rand.Reader, big.NewInt(int64(len(letters))))
		if err != nil {
			return "", err
		}
		b[i] = letters[num.Int64()]
	}
	return string(b), nil
}

// RandomStringWithCharset 生成随机字符串
func RandomStringWithCharset(n int, charset string) (string, error) {
	b := make([]rune, n)
	for i := range b {
		num, err := rand.Int(rand.Reader, big.NewInt(int64(len(charset))))
		if err != nil {
			return "", err
		}
		b[i] = rune(charset[num.Int64()])
	}
	return string(b), nil
}

func Json(v any) string {
	jsonBytes, _ := json.Marshal(v)
	return string(jsonBytes)
}
